package com.linjm.service;
import com.alibaba.fastjson.JSON;
import com.linjm.bean.UserAddress;
import com.linjm.bean.UserInfo;
import com.linjm.mapper.AddressMapper;
import com.linjm.mapper.UserMapper;
import com.linjm.util.RedisUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import redis.clients.jedis.Jedis;
import java.util.List;
@DubboService
@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private RedisUtil redisUtil;

    public String userKey_prefix="user:";
    public String userinfoKey_suffix=":info";
    public int userKey_timeOut=60*60*24;


    @Override
    public List<UserInfo> findAll() {
        return userMapper.selectAll();
    }

    @Override
    public List<UserAddress> getUserAddressList(String userId) {

        // select * from userAddress where userId=?
        UserAddress userAddress = new UserAddress();
        userAddress.setUserId(userId);
        return addressMapper.select(userAddress) ;
    }

    @Override

    public UserInfo login(UserInfo userInfo) {
        //密码用md5加密
        String passwd = userInfo.getPasswd();
        String newPasswd = DigestUtils.md5DigestAsHex(passwd.getBytes());
        userInfo.setPasswd(newPasswd);
        UserInfo info = userMapper.selectOne(userInfo);
        //登陆信息放入redis中
        String userKey=userKey_prefix+info.getId()+userinfoKey_suffix;
        if(info!=null){
            Jedis jedis = null;
            try {
                jedis = redisUtil.getJedis();
                jedis.setex(userKey, userKey_timeOut, JSON.toJSONString(info));
            } catch (Exception e) {
                e.printStackTrace();
            }
            jedis.close();
            return info;
        }
        return null;
    }

    @Override
    public UserInfo verify(String userId) {
        //缓存查询是否有redis
        Jedis jedis = null;
        try {
             jedis = redisUtil.getJedis();
            String userKey=userKey_prefix+userId+userinfoKey_suffix;
            String userJson = jedis.get(userKey);
            if (userJson!=null){
                UserInfo userInfo = JSON.parseObject(userJson, UserInfo.class);
                return userInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(jedis!=null){
                jedis.close();
            }
        }

        return null ;
    }
}
